package com.hanxiaozhang.system.service.impl;

import com.hanxiaozhang.constant.CacheName;
import com.hanxiaozhang.constant.DelFlagEnum;
import com.hanxiaozhang.result.ResultCode;
import com.hanxiaozhang.result.Result;
import com.hanxiaozhang.security.CurrentUserUtil;
import com.hanxiaozhang.system.dao.UserJobDao;
import com.hanxiaozhang.system.entity.UserJobEntity;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.hanxiaozhang.system.dao.JobDao;
import com.hanxiaozhang.system.entity.JobEntity;
import com.hanxiaozhang.system.service.JobService;
import org.springframework.transaction.annotation.Transactional;


/**
 * 岗位表
 *
 * @author hanxiaozhang
 * @email hanxiaozhang2018@sina.com
 * @date 2021-03-30
 */
@Service
public class JobServiceImpl implements JobService {

	@Resource
	private JobDao jobDao;
	@Resource
	private UserJobDao userJobDao;
	
	@Override
	public JobEntity get(Long jobId){
		return jobDao.get(jobId);
	}
	
	@Override
	public List<JobEntity> list(Map<String, Object> map){
		return jobDao.list(map);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = {CacheName.CURRENT_USER_BY_USER_ID_2HOUR}, allEntries = true)
	public int save(JobEntity job){
		job.setCreateBy(CurrentUserUtil.getUserName())
				.setCreateDate(LocalDateTime.now())
				.setDelFlag(DelFlagEnum.NORMAL.getCode());
		return jobDao.save(job);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = {CacheName.CURRENT_USER_BY_USER_ID_2HOUR}, allEntries = true)
	public int update(JobEntity job){
		job.setUpdateBy(CurrentUserUtil.getUserName())
				.setUpdateDate(LocalDateTime.now());
		return jobDao.update(job);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = {CacheName.CURRENT_USER_BY_USER_ID_2HOUR}, allEntries = true)
	public Result remove(Long jobId){
		List<UserJobEntity> list = userJobDao.listByJobId(jobId);
		if (!list.isEmpty()) {
			return Result.error(ResultCode.DATA_EXISTED_RELATION);
		}
		jobDao.remove(jobId);
		return Result.success();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = {CacheName.CURRENT_USER_BY_USER_ID_2HOUR}, allEntries = true)
	public Result batchRemove(Long[] jobIds){

		List<UserJobEntity> list = userJobDao.listByJobIds(Arrays.asList(jobIds));
		if (!list.isEmpty()) {
			return Result.error(ResultCode.DATA_EXISTED_RELATION);
		}
		jobDao.batchRemove(jobIds);
		return Result.success();
	}

}
